package org.smart4j.framework.common.threadlocal;

import com.google.common.collect.Maps;

import java.util.Collections;
import java.util.Map;
import java.util.Objects;

/**
 * 手写山寨的ThreadLocal
 *
 * @author YooLin1c
 * @version 1.0.0
 * @since 2018-02-04 13:24
 */
public class MyThreadLocal<T> {
    /**
     * 线程安全的容器（同步Map：synchronized 线程加锁）
     */
    private Map<Thread, T> container = Collections.synchronizedMap(Maps.newHashMap());

    /**
     * 绑定当前线程的值
     *
     * @param value 值
     */
    public void set(T value) {
        container.put(Thread.currentThread(), value);
    }

    /**
     * 获取当前线程的值
     *
     * @return
     */
    public T get() {
        T value = container.get(Thread.currentThread());
        if (Objects.isNull(value) || !container.containsKey(Thread.currentThread())) {
            value = this.initialValue();
            container.put(Thread.currentThread(), value);
        }
        return value;
    }

    /**
     * 移除当前线程的值
     */
    public void remove() {
        container.remove(Thread.currentThread());
    }

    /**
     * 当前线程初始值
     *
     * @return
     */
    protected T initialValue() {
        return null;
    }
}
